<?php
    // put all controller wide functions in here. like filters
    class Application extends ActionController 
    {        
        // check if session has been set,
		// otherwise attempt to log user in via cookie
		function is_logged_in($redirect=true)
		{             
			// check cookies first           
			if(!empty($_SESSION['user_id']) 
			&& ctype_digit($_SESSION['user_id'])
			&& $_SESSION['user_id'] > 0){    
				return true;
			} else { 
				use_pixel_lib('class.cookie.php');
				$cookie = new clsCookie('pixelapp');
				$cookie->init();
				$secret_user   = create_hash('user_login'.COOKIECRYPTKEY.$_SERVER['REMOTE_ADDR']);
				$secret_pass   = create_hash('user_pass'.COOKIECRYPTKEY.$_SERVER['REMOTE_ADDR']);
				if(isset($cookie->aValues[$secret_user])){
					// stuff from cookie
					$pass          = $cookie->aValues[$secret_pass];               
					$login_user    = $cookie->aValues[$secret_user];

					use_model('users');
					$u = new Users();
					if ( !$u->authenticate_by_cookie($login_user,$pass) )
					{
						if ($redirect) $this->redirect_to_login();
						return false;
					}
					session_regenerate_id();
					$_SESSION['user_id'] = $u->get('id');
					// try the page again now with the session set.
					header("Location: ".htmlspecialchars($_SERVER['REQUEST_URI']));
					return true;
				}
				if ($redirect) $this->redirect_to_login();
				return false;
			}
		}
        
		// logout user and destroy the session
        function logout_user()
        {
            $_SESSION = array();
            session_destroy();
            //*
            use_pixel_lib('class.cookie.php');
            $cookie = new clsCookie('pixelapp');
            $cookie->init();
            $cookie->destroy();
            //*/
            
        }
        
        function redirect_to_login()
        {
            $_SESSION['login_referrer'] = htmlspecialchars($_SERVER['REQUEST_URI']);
            $this->redirect_to(get_installed_path().'/login');
        }
        
    }

?>